package com.example.zk2.frag

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.zk2.GlideUtils
import com.example.zk2.R
import com.example.zk2.adapter.CateAdapter
import com.example.zk2.adapter.GoodsAdapter
import com.example.zk2.databinding.FragmentBlankBinding
import com.example.zk2.entity.CateEntity
import com.example.zk2.entity.GoodsEntity
import com.example.zk2.mvvm.BaseFragment
import com.youth.banner.loader.ImageLoader

class BlankFragment : BaseFragment<FragmentBlankBinding,HomeViewModel>() {
    val imglist = mutableListOf<String>()
    val catelist = mutableListOf<CateEntity>()
    lateinit var cateAdapter: CateAdapter
    val goodslist = mutableListOf<GoodsEntity>()
    lateinit var goodsAdapter: GoodsAdapter
    var cateId = 14
    var page=1
    override fun getLayout(): Int  = R.layout.fragment_blank

    override fun getViewModel(): Class<HomeViewModel> = HomeViewModel::class.java

    override fun initView() {
        viewModel.banner()

        cateAdapter = CateAdapter(catelist)
        binding.cateRv.adapter = cateAdapter
        binding.cateRv.layoutManager = GridLayoutManager(context,5)
        viewModel.cate()

        goodsAdapter = GoodsAdapter(goodslist)
        binding.goodsRv.adapter = goodsAdapter
        binding.goodsRv.layoutManager = LinearLayoutManager(context)
        viewModel.goods(cateId,page,10)

    }

    override fun initData() {
        viewModel.banSuccess.observe(this){
            if(it.code==200){
                it.data.forEach {
                    imglist.add(it.imagePath)
                }
                binding.ban.setImages(imglist)
                binding.ban.setImageLoader(object :ImageLoader(){
                    override fun displayImage(
                        context: Context?,
                        path: Any?,
                        imageView: ImageView?
                    ) {
                        if(context!=null&&imageView!=null){
                            GlideUtils.loadPic(context,path!!.toString(),imageView)
                        }
                    }
                })
                binding.ban.start()
            }
        }

        viewModel.cateSuccess.observe(this){
            if(it.code==200){
                val data = it.data
                val cateData = data[0]
                catelist.addAll(cateData.data)
                cateAdapter.notifyDataSetChanged()
            }
        }
        viewModel.goodsSuccess.observe(this){
            if(it.code==200){
                if(page==1){
                    goodslist.clear()
                }
                goodslist.addAll(it.data)
                goodsAdapter.notifyDataSetChanged()
            }
        }
    }

}